package com.cl.code.database.mybatis.module.sql.table;


import com.cl.code.database.mybatis.module.annotation.LogicDelete;
import com.cl.code.database.mybatis.module.annotation.Table;
import com.cl.code.database.mybatis.module.annotation.TableId;
import com.cl.code.database.mybatis.module.annotation.Version;
import com.cl.code.database.mybatis.util.TextUtils;

import java.lang.reflect.Field;
import java.util.Locale;

/**
 * @author chengliang
 * @since 1.0.0
 */
public class TableInfoParser {

    public static String parseTableName(Class<?> clazz) {
        Class<Table> tableAnnotationClass = Table.class;
        boolean annotationPresent = clazz.isAnnotationPresent(tableAnnotationClass);
        String tableName;
        if (annotationPresent) {
            Table annotation = clazz.getAnnotation(tableAnnotationClass);
            tableName = annotation.value();
            if (!tableName.isEmpty()) {
                return tableName;
            }
        }
        tableName = clazz.getSimpleName().toLowerCase(Locale.ROOT);
        return tableName;
    }

    public static TableField[] parseTableField(Class<?> clazz) {
        Field[] declaredFields = clazz.getDeclaredFields();
        TableField[] tableFields = new TableField[declaredFields.length];
        for (int i = 0; i < declaredFields.length; i++) {
            Field declaredField = declaredFields[i];
            String fieldName = declaredField.getName();
            if (declaredField.isAnnotationPresent(TableId.class)) {
                tableFields[i] = new IdField(fieldName, TextUtils.toSnakeCase(fieldName), declaredField);
            } else if (declaredField.isAnnotationPresent(Version.class)) {
                tableFields[i] = new VersionField(fieldName, TextUtils.toSnakeCase(fieldName), declaredField);
            } else if (declaredField.isAnnotationPresent(LogicDelete.class)) {
                tableFields[i] = new LogicDeleteField(fieldName, TextUtils.toSnakeCase(fieldName), declaredField);
            } else {
                tableFields[i] = new NormalField(fieldName, TextUtils.toSnakeCase(fieldName), declaredField);
            }
        }
        return tableFields;
    }


}
